<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="1000px" top="10px" @close='close'>
    <div class="dialogContentBoxMaxHeight100">
      <el-form ref="form" :model="record" label-width="120px" :rules="rules" class="ipsForm" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:400px;" size='small' id="white-dialog-name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" ref="desc" style="width:400px;" size='small' id="white-dialog-desc" :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <div class="strategyFatherBox">
          <el-select v-model="ruleType" ref="ruleType" size='small' style="width:150px;">
            <el-option v-for="(value,key) in ruleArray.rule" :key="key" :label="$t(value)" :value="key" :id="`white-dialog-rule-${key}`">
              <el-tooltip placement="right-start" :open-delay="500">
                <div slot="content">
                  {{ $t(ruleArray.ruleTip[key]) }}
                </div>
                <div>{{ $t(value) }}</div>
              </el-tooltip>
            </el-option>
          </el-select>
          <el-upload v-show="ruleType === 'OPCDA' && !record.id" class="upload-opc" ref="upload" :action="global + '/whitelist/addWhitelist'" :file-list='fileList' :before-remove='whitelistBeforeRemove' :on-success="whitelistOnSuccess" :show-file-list='false' :data='record' :headers='headerConfig' :multiple='false' :on-change="handleChange" accept='.txt,.doc.,.docx' :auto-upload='false'>
            <el-button slot="trigger" size="small" type="primary" class="selectName"><i class="el-icon-upload" style="margin-right:2px;"></i>{{$t('点名导入')}}</el-button>
          </el-upload>
          <el-button type="success" size='small' @click="addConfig()">{{$t('添加规则')}}</el-button>
          <span>{{ fileList[0]?fileList[0].name:'' }}</span>
          <!-- -------------------------列表------------------------------- -->
          <s-7300-Table v-if="ruleType === 's7_300' && dialogVisible" key="s7_300" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></s-7300-Table>
          <s-7300-plus-Table v-if="ruleType === 's7_300_plus' && dialogVisible" key="s7_300_plus" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></s-7300-plus-Table>
          <modbus-Table v-if="ruleType === 'modbus' && dialogVisible" key="modbus" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></modbus-Table>
          <iec104-Table v-if="ruleType === 'iec104' && dialogVisible" key="iec104" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></iec104-Table>
          <opc-Table v-if="ruleType === 'OPCDA' && dialogVisible" key="OPCDA" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></opc-Table>
          <opcua-Table v-if="ruleType === 'opcua' && dialogVisible" key="opcua" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></opcua-Table>
          <eipcip-Table v-if="ruleType === 'eipcip' && dialogVisible" key="eipcip" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></eipcip-Table>
          <ab-Table v-if="ruleType === 'ab' && dialogVisible" key="ab" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></ab-Table>
          <ge-Table v-if="ruleType === 'ge' && dialogVisible" key="ge" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></ge-Table>
          <dnp3-Table v-if="ruleType === 'dnp3' && dialogVisible" key="dnp3" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></dnp3-Table>
          <smart200-Table v-if="ruleType === 'smart200' && dialogVisible" key="smart200" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></smart200-Table>
          <s5-Table v-if="ruleType === 's5' && dialogVisible" key="s5" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></s5-Table>
          <ge-snpx-Table v-if="ruleType === 'ge_snpx' && dialogVisible" key="ge_snpx" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></ge-snpx-Table>
          <omron-Table v-if="ruleType === 'omron' && dialogVisible" key="omron" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></omron-Table>
          <rtsp-Table v-if="ruleType === 'rtsp' && dialogVisible" key="rtsp" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></rtsp-Table>
          <bacnet-Table v-if="ruleType === 'bacnet' && dialogVisible" key="bacnet" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></bacnet-Table>
          <sanling-Table v-if="ruleType === 'sanling' && dialogVisible" key="sanling" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></sanling-Table>
          <commserver-Table v-if="ruleType === 'commserver' && dialogVisible" key="commserver" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></commserver-Table>
          <mitsubishi-Table v-if="ruleType === 'mitsubishi' && dialogVisible" key="mitsubishi" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></mitsubishi-Table>
          <cdt-Table v-if="ruleType === 'cdt' && dialogVisible" key="cdt" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></cdt-Table>
          <dlt645-Table v-if="ruleType === 'dlt645' && dialogVisible" key="dlt645" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></dlt645-Table>
          <iec101-Table v-if="ruleType === 'iec101' && dialogVisible" key="iec101" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></iec101-Table>
          <egd-table v-if="ruleType === 'EGD' && dialogVisible" key="EGD" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></egd-table>
          <cimplicity-table v-if="ruleType === 'cimplicity' && dialogVisible" key="cimplicity" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></cimplicity-table>
          <pniocm-table v-if="ruleType === 'pnio_cm' && dialogVisible" key="pnio_cm" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></pniocm-table>
          <mms-table v-if="ruleType === 'MMS' && dialogVisible" key="MMS" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></mms-table>
          <custom-table v-if="ruleType === 'custom' && dialogVisible" key="custom" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></custom-table>
          <mysql-table v-if="ruleType === 'mysql' && dialogVisible" key="mysql" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></mysql-table>
          <enip-table v-if="ruleType === 'enip' && dialogVisible" key="enip" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></enip-table>
          <cip-table v-if="ruleType === 'cip' && dialogVisible" key="cip" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></cip-table>
          <cipmb-table v-if="ruleType === 'cipmb' && dialogVisible" key="cipmb" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap'></cipmb-table>
          <mqtt-table v-if="ruleType === 'mqtt' && dialogVisible" key="mqtt" :ruleMap='record.rule_map' @largeConfig='addConfig' @delRuleMap='delRuleMap' @childrenUpdataRule='childrenUpdataRule'></mqtt-table>
          <!-- ------------------------------------------------------------ -->

        </div>
      </el-form>

      <!-- -------------------------添加和编辑----------------------------- -->
      <s-7300-dialog v-if="ruleDialogVisible && ruleType === 's7_300'" ref="s7_300" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></s-7300-dialog>
      <s-7300-plus-dialog v-if="ruleDialogVisible && ruleType === 's7_300_plus'" ref="s7_300_plus" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></s-7300-plus-dialog>
      <modbus-dialog v-if="ruleDialogVisible && ruleType === 'modbus'" ref="modbus" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></modbus-dialog>
      <iec104-dialog v-if="ruleDialogVisible && ruleType === 'iec104'" ref="iec104" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></iec104-dialog>
      <opc-dialog v-if="ruleDialogVisible && ruleType === 'OPCDA'" ref="OPCDA" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></opc-dialog>
      <opcua-dialog v-if="ruleDialogVisible && ruleType === 'opcua'" ref="opcua" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></opcua-dialog>
      <eipcip-dialog v-if="ruleDialogVisible && ruleType === 'eipcip'" ref="eipcip" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></eipcip-dialog>
      <ab-dialog v-if="ruleDialogVisible && ruleType === 'ab'" ref="ab" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></ab-dialog>
      <ge-dialog v-if="ruleDialogVisible && ruleType === 'ge'" ref="ge" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></ge-dialog>
      <dnp3-dialog v-if="ruleDialogVisible && ruleType === 'dnp3'" ref="dnp3" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></dnp3-dialog>
      <smart200-dialog v-if="ruleDialogVisible && ruleType === 'smart200'" ref="smart200" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></smart200-dialog>
      <s5-dialog v-if="ruleDialogVisible && ruleType === 's5'" ref="s5" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></s5-dialog>
      <ge-snpx-dialog v-if="ruleDialogVisible && ruleType === 'ge_snpx'" ref="ge_snpx" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></ge-snpx-dialog>
      <omron-dialog v-if="ruleDialogVisible && ruleType === 'omron'" ref="omron" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></omron-dialog>
      <rtsp-dialog v-if="ruleDialogVisible && ruleType === 'rtsp'" ref="rtsp" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></rtsp-dialog>
      <bacnet-dialog v-if="ruleDialogVisible && ruleType === 'bacnet'" ref="bacnet" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></bacnet-dialog>
      <sanling-dialog v-if="ruleDialogVisible && ruleType === 'sanling'" ref="sanling" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></sanling-dialog>
      <commserver-dialog v-if="ruleDialogVisible && ruleType === 'commserver'" ref="commserver" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></commserver-dialog>
      <mitsubishi-dialog v-if="ruleDialogVisible && ruleType === 'mitsubishi'" ref="mitsubishi" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></mitsubishi-dialog>
      <cdt-dialog v-if="ruleDialogVisible && ruleType === 'cdt'" ref="cdt" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></cdt-dialog>
      <dlt645-dialog v-if="ruleDialogVisible && ruleType === 'dlt645'" ref="dlt645" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></dlt645-dialog>
      <iec101-dialog v-if="ruleDialogVisible && ruleType === 'iec101'" ref="iec101" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></iec101-dialog>
      <egd-dialog v-if="ruleDialogVisible && ruleType === 'EGD'" ref="EGD" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></egd-dialog>
      <cimplicity-dialog v-if="ruleDialogVisible && ruleType === 'cimplicity'" ref="cimplicity" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></cimplicity-dialog>
      <pniocm-dialog v-if="ruleDialogVisible && ruleType === 'pnio_cm'" ref="pnio_cm" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></pniocm-dialog>
      <mms-dialog v-if="ruleDialogVisible && ruleType === 'MMS'" ref="MMS" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></mms-dialog>
      <custom-dialog v-if="ruleDialogVisible && ruleType === 'custom'" ref="custom" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose' @updateCustomRuleMap='updateCustomRuleMap'></custom-dialog>
      <mysql-dialog v-if="ruleDialogVisible && ruleType === 'mysql'" ref="mysql" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></mysql-dialog>
      <enip-dialog v-if="ruleDialogVisible && ruleType === 'enip'" ref="enip" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></enip-dialog>
      <cip-dialog v-if="ruleDialogVisible && ruleType === 'cip'" ref="cip" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></cip-dialog>
      <cipmb-dialog v-if="ruleDialogVisible && ruleType === 'cipmb'" ref="cipmb" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose'></cipmb-dialog>
      <mqtt-dialog v-if="ruleDialogVisible && ruleType === 'mqtt'" ref="mqtt" @addConfigRuleMap='addConfigRuleMap' @childrenClose='childrenClose' @childrenUpdataRule='childrenUpdataRule'></mqtt-dialog>
      <!-- --------------------------------------------------------------- -->
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import global from '@/global'
import { getSessionId } from '@/utils/auth'
import { addRule, editRule, delRule, addWhitelist, editWhitelist, getWhiteInfo, addWhitelistCustomRule, editWhitelistCustomRule } from '@/api/safe/white'
import {
  s7300Dialog,
  s7300Table,
  modbusDialog,
  modbusTable,
  iec104Dialog,
  iec104Table,
  opcDialog,
  opcTable,
  opcuaDialog,
  opcuaTable,
  eipcipDialog,
  eipcipTable,
  abDialog,
  abTable,
  geDialog,
  geTable,
  dnp3Dialog,
  dnp3Table,
  smart200Dialog,
  smart200Table,
  s5Dialog,
  s5Table,
  geSnpxDialog,
  geSnpxTable,
  omronDialog,
  omronTable,
  rtspDialog,
  rtspTable,
  bacnetDialog,
  bacnetTable,
  sanlingDialog,
  sanlingTable,
  commserverDialog,
  commserverTable,
  mitsubishiDialog,
  mitsubishiTable,
  cdtDialog,
  cdtTable,
  dlt645Dialog,
  dlt645Table,
  iec101Dialog,
  iec101Table,
  egdDialog,
  egdTable,
  cimplicityDialog,
  cimplicityTable,
  pniocmDialog,
  pniocmTable,
  customDialog,
  customTable,
  s7300PlusDialog,
  s7300PlusTable,
  mmsDialog,
  mmsTable,
  mysqlDialog,
  mysqlTable,
  enipDialog,
  enipTable,
  cipDialog,
  cipTable,
  cipmbDialog,
  cipmbTable,
  mqttDialog,
  mqttTable
} from './components'
import ruleArray from './ruleArray'
import { inputClass, texttextClass, selectClass } from '@/utils/input-class.js'

export default {
  components: {
    s7300Dialog,
    s7300Table,
    modbusDialog,
    modbusTable,
    iec104Dialog,
    iec104Table,
    opcDialog,
    opcTable,
    opcuaDialog,
    opcuaTable,
    eipcipDialog,
    eipcipTable,
    abDialog,
    abTable,
    geDialog,
    geTable,
    dnp3Dialog,
    dnp3Table,
    smart200Dialog,
    smart200Table,
    s5Dialog,
    s5Table,
    geSnpxDialog,
    geSnpxTable,
    omronDialog,
    omronTable,
    rtspDialog,
    rtspTable,
    bacnetDialog,
    bacnetTable,
    sanlingDialog,
    sanlingTable,
    commserverDialog,
    commserverTable,
    mitsubishiDialog,
    mitsubishiTable,
    cdtDialog,
    cdtTable,
    dlt645Dialog,
    dlt645Table,
    iec101Dialog,
    iec101Table,
    egdDialog,
    egdTable,
    cimplicityDialog,
    cimplicityTable,
    pniocmDialog,
    pniocmTable,
    customDialog,
    customTable,
    s7300PlusDialog,
    s7300PlusTable,
    mmsDialog,
    mmsTable,
    mysqlDialog,
    mysqlTable,
    enipDialog,
    enipTable,
    cipDialog,
    cipTable,
    cipmbDialog,
    cipmbTable,
    mqttDialog,
    mqttTable
  },
  name: 'WhiteDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      ruleDialogVisible: false,
      fileList: [],
      headerConfig: {
        'session_id': getSessionId()
      },
      global: global.BASE_URL,
      record: {
        id: '',
        name: '',
        old_name: '',
        rule_map: [],
        desc: ''
      },
      recordCopy: {
        id: '',
        name: '',
        old_name: '',
        rule_map: [],
        desc: ''
      },
      connectList: {
        's7_300_connect': 's7_300',
        'modbus_connect': 'modbus',
        'iec104_connect': 'iec104',
        'OPCDA_CONNECT': 'OPCDA'
      },
      ruleArray: ruleArray,
      showPositionList: ['I', 'Q', 'M', 'DB', 'DI'],
      showIecSelectList: ['45', '46', '47', '58', '59', '60'],
      showOther: ['0x04', '0x05'],
      ruleType: 'ab',
      type: false, // 编辑完关闭页面时刷新列表
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        const textdata = ['desc']
        const selectData = ['ruleType']
        selectClass(this.$refs, selectData)
        inputClass(this.$refs, data)
        texttextClass(this.$refs, textdata)
      })
      if (data) {
        getWhiteInfo({ name: data.name }).then(res => {
          if (res.status === 0) {
            res.info[0].old_name = res.info[0].name
            
            this.record = JSON.parse(JSON.stringify(res.info[0]))
            this.recordChange(res.info[0], true)
            // this.record = res.info[0]
          }
        })
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if ((this.record.rule_map.length > 0 && this.record.rule_map.length < 64) || (this.fileList && this.fileList.length > 0 && this.record.rule_map.length < 64)) {
            var formData = this.recordsubmit(this.record)
            // var formData = Object.assign({}, this.record)
            delete formData.rule_map.rows
            formData.rule_map = JSON.stringify(formData.rule_map)
            if (this.record.id) {
              editWhitelist(formData).then(res => {
                if (res.status === 0) {
                  this.$messages.success(this.$t('编辑成功'))
                  this.type = false
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              if (this.fileList && this.fileList.length > 0) {
                this.$refs.upload.submit()
              } else {
                addWhitelist(formData).then(res => {
                  if (res.status === 0) {
                    this.$messages.success(this.$t('添加成功'))
                    this.type = false
                    this.close()
                    this.$parent.listData()
                  }
                })
              }
            }
          } else if (this.record.rule_map.length < 1) {
            this.$message({
              message: this.$t('规则不能为空'),
              type: 'error'
            })
          } else {
            this.$message({
              message: this.$t('添加规则不能超过63个'),
              type: 'error'
            })
          }
        }
      })
    },
    // 添加规则按钮
    addConfig (data) {
      this.ruleDialogVisible = true
      this.$nextTick(() => {
        this.$refs[this.ruleType].init(data, this.record.old_name)
      })
    },
    addConfigRuleMap (data) {
      if (data.rule_id) {
        this.editRuleMap(data)
      } else {
        this.addRuleMap(data)
      }
    },
    close () {
      this.$refs.upload.clearFiles()
      this.dialogVisible = false
      this.ruleType = 'ab'
      this.fileList = []
      this.record = Object.assign({}, this.recordCopy)
      this.record.rule_map = []
      this.$refs.form.resetFields()
      if (this.type) {
        this.$parent.listData()
        this.type = false
      }
    },
    childrenClose () {
      this.ruleDialogVisible = false
    },
    childrenUpdataRule () {
      if(this.record.old_name != '')
      {
        this.updateRuleMap()
      }
        
    },
    addRuleMap (data) {
      if (this.record.id && data.proto === 'custom') {
        let formRule = JSON.parse(JSON.stringify(data))
        formRule.rule_id = this.record.rule_map.length + 1
        let formData = {
          name: this.record.old_name,
          rule_map: JSON.stringify([formRule])
        }
        // delete formData.rule_map.rows
        addWhitelistCustomRule(formData).then(res => {
          if (res.status === 0) {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.$refs[this.ruleType].close()
            this.ruleDialogVisible = false
            this.updateRuleMap()
          }
        })
      } else if (this.record.id) {
      if (this.record.id) {
          if(!data.rule_id   && this.record.rule_map.length > 0)
          {
            data.rule_id = this.record.rule_map[this.record.rule_map.length - 1].rule_id + 1;
          }
          else if(!data.rule_id && this.record.rule_map.length == 0)
          {
            data.rule_id = 1;
          }
        }
        let formData = {
          name: this.record.old_name,
          rule_map: JSON.parse(JSON.stringify(data)),
          rule_type: data.proto
        }
        formData.rule_map = JSON.stringify(this.ruleMapChange(formData.rule_map))
        delete formData.rule_map.rows
        addRule(formData).then(res => {
          if (res.status === 0) {
            this.$message({
              message: this.$t('添加成功'),
              type: 'success'
            })
            this.$refs[this.ruleType].close()
            this.ruleDialogVisible = false
            this.updateRuleMap()
          }
        })
      } else {
        this.$refs[this.ruleType].close()
        this.ruleDialogVisible = false
        this.record.rule_map.push(data)
        this.ruleIdChange()
      }
    },
    editRuleMap (data) {
      if (this.record.id && data.proto === 'custom') {
        let formData = {
          name: this.record.old_name,
          rule_id: data.rule_id,
          rule_name: data.rule_name,
          action: data.action,
          desc: data.desc
        }
        editWhitelistCustomRule(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success('编辑成功')
            this.$refs[this.ruleType].close()
            this.ruleDialogVisible = false
            this.updateRuleMap()
          }
        })
      } else if (this.record.id) {
        let formData = {
          name: this.record.old_name,
          rule_id: data.rule_id,
          rule_map: JSON.parse(JSON.stringify(data)),
          rule_type: data.proto
        }
        formData.rule_map = JSON.stringify(this.ruleMapChange(formData.rule_map))
        delete formData.rule_map.rows
        editRule(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('编辑成功'))
            this.$refs[this.ruleType].close()
            this.ruleDialogVisible = false
            this.updateRuleMap()
          }
        })
      } else {
        this.$refs[this.ruleType].close()
        this.ruleDialogVisible = false
        this.record.rule_map.splice(data.rule_id - 1, 1, data)
        this.ruleIdChange()
      }
    },
    delRuleMap (data) {
      this.$confirm(this.$t('您是否要删除所选中的规则？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        if (this.record.id) {
          delRule({ name: this.record.old_name, rule_id: data.rule_id }).then(res => {
            if (res.status === 0) {
              this.$messages.success(this.$t('删除成功'))
              this.updateRuleMap()
            }
          })
        } else {
          this.record.rule_map.splice(data.rule_id - 1, 1)
          this.ruleIdChange()
        }
      })
    },
    // 更新列表
    updateRuleMap () {
      getWhiteInfo({ name: this.record.old_name }).then(res => {
        if (res.status === 0) {
          let record = JSON.parse(JSON.stringify(res.info[0]))
          this.record.rule_map = record.rule_map
          this.recordChange(res.info[0], false)
          // this.record = res.info[0]
        }
      })
      this.type = true
    },
    // 更新自定义添加特征时的列表
    updateCustomRuleMap () {
      getWhiteInfo({ name: this.record.old_name }).then(res => {
        if (res.status === 0) {
          let record = JSON.parse(JSON.stringify(res.info[0]))
          this.record.rule_map = record.rule_map
          this.$refs[this.ruleType].updateCustomRuleMap(record.rule_map)
        }
      })
      this.type = true
    },
    // 重新分配规则id
    ruleIdChange () {
      this.record.rule_map.forEach((tab, index) => {
        tab.rule_id = index + 1
      })
    },
    recordChange (data, type) {
      // s7 300 把拿到的格式换成能操作的格式
      // this.record = JSON.parse(JSON.stringify(data))
      if (type && this.record.rule_map.length > 0) {
        this.ruleType = this.connectList[this.record.rule_map[0].proto] ? this.connectList[this.record.rule_map[0].proto] : (this.record.rule_map[0].proto ? this.record.rule_map[0].proto : '自定义')
      }
      this.record.rule_map.forEach(val => {
        console.log('显示页面内容1', val);
        switch (val.proto) {
          case 's7_300':
            val.func = '0x' + '00'.substr(0, (2 - val.func.toString(16).length)) + val.func.toString(16).toUpperCase()
            if (val.accept_range === 'single') {
              var db_num = val.db_num.split(',')
              var register_address_range = val.register_address_range.split(',')
              var register_interval = val.register_interval.split(',')
              var register_value_range = val.register_value_range.split(',')
              var register_value_type = val.register_value_type.split(',')
              val.rows = []
              register_interval.forEach((value, index) => {
                var end = register_address_range[index].split('~')[1] || ''
                var start = register_address_range[index].split('~')[0] || ''
                val.rows.push({
                  db_num: db_num[index] || 0,
                  register_address_end: end.split('.')[0] || '',
                  register_address_end_position: end.split('.')[1] || '0',
                  register_address_start: start.split('.')[0] || '',
                  register_address_start_position: start.split('.')[1] || '0',
                  register_interval: value,
                  register_value_range_start: register_value_type[index] === '3' ? '' : (register_value_range[index] ? register_value_range[index].split('~')[0] : ''),
                  register_value_range_end: register_value_type[index] === '3' ? '' : (register_value_range[index] ? register_value_range[index].split('~')[1] : ''),
                  register_value_range_select: register_value_type[index] === '3' ? (register_value_range[index] ? register_value_range[index].split('~')[0] : '0') : '0',
                  register_value_type: register_value_type[index] || '0',
                  rule_id: index + 1
                })
              })
            }
            break
          case 's7_300_connect':
            val.operate_type = 1
            var read_register_value_range = val.read_register_value_range.split('~')
            val.read_register_value_type = String(val.read_register_value_type)
            if (val.read_register_value_type === '3') {
              val.register_value_range_select = read_register_value_range[0]
            } else {
              val.register_value_range_start = read_register_value_range[0]
              val.register_value_range_end = read_register_value_range[1]
            }
            if (this.showPositionList.includes(val.relate_write_register_interval)) {
              val['write_register_address_range_position'] = val.write_register_address_range.split('.')[1] ? val.write_register_address_range.split('.')[1] : '0'
              val.write_register_address_range = val.write_register_address_range.split('.')[0]
            } else {
              val['write_register_address_range_position'] = '0'
            }
            if (this.showPositionList.includes(val.relate_read_register_interval)) {
              val['read_register_address_range_position'] = val.read_register_address_range.split('.')[1] ? val.read_register_address_range.split('.')[1] : '0'
              val.read_register_address_range = val.read_register_address_range.split('.')[0]
            } else {
              val['read_register_address_range_position'] = '0'
            }

            break
          case 'modbus':
            if (val.func === '0' || val.func === 0) {
              val.operate_type = '1'
            } else {
              val.operate_type = '0'
            }
            val.register_value_range_start = val.register_value_range.split('-')[0] || ''
            val.register_value_range_end = val.register_value_range.split('-')[1] || ''
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'modbus_connect':
            val.operate_type = '2'
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'iec104':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            if (data.type === '0') {
              if (this.showIecSelectList.includes(val.func)) {
                val.register_value_range_select = val.register_value_range.split('-')[0] || ''
              } else {
                val.register_value_range_start = val.register_value_range.split('-')[0] || ''
                val.register_value_range_end = val.register_value_range.split('-')[1] || ''
              }
            }
            break
          case 'iec104_connect':
            val.operate_type = '1'
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            if (this.showIecSelectList.includes(val.be_relate_func)) {
              val.register_value_range_select_between = val.be_relate_register_value_range.split('-')[0] || ''
            } else {
              val.register_value_range_start_between = val.be_relate_register_value_range.split('-')[0] || ''
              val.register_value_range_end_between = val.be_relate_register_value_range.split('-')[1] || ''
            }
            break
          case 'OPCDA':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            // val.register_value_range_select = val.value_range.split('~')[0] || '0'
            // val.value_range_start = val.value_range.split('~')[0] || ''
            // val.value_range_end = val.value_range.split('~')[1] || ''
            break
          case 'OPCDA_CONNECT':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            // val.register_value_range_select_write = val.relate_value_range.split('~')[0] || '0'
            // val.value_range_start_write = val.relate_value_range.split('~')[0] || ''
            // val.value_range_end_write = val.relate_value_range.split('~')[1] || ''
            val.operate_type = 1
            break
          case 'opcua':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            val.register_value_range_select = val.value_range.split('~')[1] || '0'
            val.value_range_start = val.value_range.split('~')[0] || ''
            val.value_range_end = val.value_range.split('~')[1] || ''
            break
          case 'eipcip':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            val.register_value_range_select = val.value_range.split('~')[0] || '0'
            val.value_range_start = val.value_range.split('~')[0] || ''
            val.value_range_end = val.value_range.split('~')[1] || ''
            break
          case 'ge':
            val.communication_type = '0x' + '0000'.substr(0, (4 - val.communication_type.toString(16).length)) + val.communication_type.toString(16).toUpperCase()
            val.register_type = '0x' + '00'.substr(0, (2 - val.register_type.toString(16).length)) + val.register_type.toString(16).toLowerCase()
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'dnp3':
            val.func = '0x' + '00'.substr(0, (2 - val.func.toString(16).length)) + val.func.toString(16).toUpperCase()
            break
          case 'sanling':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'commserver':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'mitsubishi':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'pnio_cm':
            val['func'] = val['data_type']
            break
          case 's7_300_plus':
            val['register_address_max_position'] = val['register_address_max'] & 7
            val['register_address_min_position'] = val['register_address_min'] & 7
            val['register_address_max'] = val['register_address_max'] >> 3
            val['register_address_min'] = val['register_address_min'] >> 3
            if (val.func !== 0) {
              val.func = '0x' + '0000'.substr(0, (4 - val.func.toString(16).length)) + val.func.toString(16).toLowerCase()
            } else {
              val.func = ''
            }
            if (val.register_interval !== 0) {
              val.register_interval = '0x' + '00'.substr(0, (2 - val.register_interval.toString(16).length)) + val.register_interval.toString(16).toLowerCase()
            } else {
              val.register_interval = ''
            }
            break
          case 'MMS':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          case 'cip':
            val.tag_type = val.TagType
            val.commond_describe_type_name = []
            for (let item of val.CommDesTypeName) {
              let valueList = item.array_info.split('-')
              val.commond_describe_type_name.push({
                commond: valueList[0],
                describe: valueList[1],
                type: valueList[2],
                name: valueList[3]
              })
            }
            break
          case 'enip':
            for (const key in val) {
              if (typeof val[key] === 'number') {
                val[key] = String(val[key])
              }
            }
            break
          default:
            break
        }
      })
    },
    recordsubmit (data) {
      // s7 300 把拿到的格式换成能提交的格式
      let formData = JSON.parse(JSON.stringify(data))
      formData.rule_map.forEach(val => {
        val = this.ruleMapChange(val)
      })
      return formData
    },
    ruleMapChange (data) {
      let val = data
      switch (val.proto) {
        case 's7_300':
          if (this.showOther.includes(val.func) && val.rows && val.rows.length > 0) {
            val.db_num = ''
            val.register_address_range = ''
            val.register_interval = ''
            val.register_value_range = ''
            val.register_value_type = ''
            val.rows.forEach((value, index) => {
              // 判断是不是第一个，第一个前面不加逗号
              if (index !== 0) {
                val.db_num += ','
                val.register_address_range += ','
                val.register_interval += ','
                val.register_value_range += ','
                val.register_value_type += ','
              }
              val.db_num += value.db_num || 0
              // 寄存器范围地址
              if (this.showPositionList.includes(value.register_interval)) {
                val.register_address_range += value.register_address_start + '.' + value.register_address_start_position + '~' + value.register_address_end + '.' + value.register_address_end_position
              } else {
                val.register_address_range += value.register_address_start + '~' + value.register_address_end
              }
              val.register_interval += value.register_interval
              if (val.func !== 4 && val.func !== '0x04') { // 如果是读寄存器就没有寄存器范围
                // 寄存器值范围
                if (value.register_value_type === '3') {
                  val.register_value_range += value.register_value_range_select + '~' + value.register_value_range_select
                } else {
                  val.register_value_range += value.register_value_range_start + '~' + value.register_value_range_end
                }
                val.register_value_type += value.register_value_type
              }
            })
            // val.db_num = val.db_num
            // val.register_address_range = val.register_address_range.substring(0, val.register_address_range.length - 1)
            // val.register_interval = val.register_interval.substring(0, val.register_interval.length - 1)
            // val.register_value_range = val.register_value_range.substring(0, val.register_value_range.length - 1)
            // val.register_value_type = val.register_value_type.substring(0, val.register_value_type.length - 1)
            delete val.rows
          }
          val.func = parseInt(val.func, 16)
          break
        case 's7_300_plus':
          val['register_address_max'] = val['register_address_max'] << 3 | val['register_address_max_position']
          val['register_address_min'] = val['register_address_min'] << 3 | val['register_address_min_position']
          val.func = parseInt(val.func, 16)
          break
        case 's7_300_connect':
          if (this.showPositionList.includes(val.relate_write_register_interval)) {
            val.write_register_address_range = val.write_register_address_range + '.' + val.write_register_address_range_position
          }
          if (this.showPositionList.includes(val.relate_read_register_interval)) {
            val.read_register_address_range = val.read_register_address_range + '.' + val.read_register_address_range_position
          }
          break
        case 'cip':
          var str = ''
          val.commond_describe_type_name.forEach(val => {
            if (str !== '') {
              str += '/'
            }
            str += val.commond + '-' + val.describe + '-' + val.type + '-' + val.name
          })
          val.commond_describe_type_name = str
          break
        default:
          break
      }
      return val
    },
    handleChange (file, fileList) {
      const istxt = file.name.indexOf('.txt') >= 0
      const isTXT = file.name.indexOf('.TXT') >= 0
      if (!isTXT && !istxt) {
        fileList.splice(-1, 1)
        this.$messages.error(this.$t('上传的文件只能是 TXT 格式!'))
        this.fileList = fileList
      } else if (fileList.length > 1) {
        fileList.splice(0, 1)
        this.fileList = fileList
      } else {
        this.fileList = fileList
      }
    },
    beforeAvatarUpload (file) {
      const istxt = file.name.indexOf('.txt') >= 0
      const isTXT = file.name.indexOf('.TXT') >= 0

      if (!isTXT && !istxt) {
        this.$messages.error(this.$t('上传的文件只能是 TXT 格式!'))
        this.$refs.upload.abort()
      }
    },
    whitelistOnSuccess (data) {
      if (data.status === 0) {
        this.$message({
          message: this.$t('添加成功'),
          type: 'success'
        })
        this.type = false
        this.close()
        this.$parent.listData()
      } else {
        // 只有已有文件状态为准备时，再点击确定才会提交
        this.$refs.upload.fileList[0].status = 'ready'
        this.$message({
          message: data.msg,
          type: 'error'
        })
      }
    },
    whitelistBeforeRemove () {
      // return false
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style lang="less">
.ipsScrollbar {
  position: relative;

  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.upload-opc {
  display: inline-block;
}
</style>
